package com.baiduspring.web.index;

import com.baiduspring.dict.ColumnChannelEnum;
import com.baiduspring.function.elasticsearch.operation.Doc;
import com.baiduspring.function.elasticsearch.operation.QueryInput;
import com.baiduspring.service.specialcolumn.SpecialColumnIndexEnum;
import com.baiduspring.service.user.UserService;
import com.baiduspring.utils.elasticsearch.ElasticSearchUtils;
import com.baiduspring.vo.ResultsVO;
import com.baiduspring.web.user.LoginStatus;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Optional;

/**
 * 网站首页控制器
 *
 * @author xiongyan
 */
@RestController
@Scope("prototype")
@Slf4j
public class IndexController {
    @Resource
    private UserService userService;

    /**
     * 跳转到网站首页
     *
     * @return ModelAndView首页视图
     */
    @RequestMapping("/")
    public ModelAndView index(HttpServletRequest request) {
        ModelAndView view = new ModelAndView("index");
        view.addObject("topnav", "index");
        LoginStatus.status(request, view);
        view.addObject("columnChannels", ColumnChannelEnum.columnChannels().get());


        QueryInput input = new QueryInput();
        Doc<String, SortOrder> sortFields = new Doc<>();
        sortFields.field("updateDate", SortOrder.DESC);
        input.setSortFields(sortFields);

        input.setCurrentPage(1);
        input.setPageSize(10);

        String[] indies = {SpecialColumnIndexEnum.SPECIAL_COLUMN_BLOG_INDEX.getValue()};
        String[] types = {SpecialColumnIndexEnum.SPECIAL_COLUMN_BLOG_TYPE.getValue()};

        Map<String, Class> outputFields = Maps.newHashMap();
        outputFields.put("title", String.class);
        outputFields.put("orig", Integer.class);
        outputFields.put("columnChannel", Integer.class);
        outputFields.put("label", String.class);
        outputFields.put("content", String.class);
        outputFields.put("contentTxt", String.class);
        outputFields.put("authorAccount", Long.class);
        outputFields.put("status", String.class);
        outputFields.put("readNum", Integer.class);
        outputFields.put("collectNum", Integer.class);
        outputFields.put("likesNum", Integer.class);
        outputFields.put("uriMark", Long.class);
        outputFields.put("ip", String.class);
        outputFields.put("createDate", Long.class);
        outputFields.put("updateDate", Long.class);

        input.setIndices(indies);
        input.setTypes(types);
        input.setOutputFields(outputFields);

        ElasticSearchUtils.query(input, true, ResultsVO.class, output -> {
            for (Object o : output.getResults()) {
                ResultsVO vo = (ResultsVO) o;
                userService.getByAccount(vo.getAuthorAccount()).ifPresent(user -> vo.setUser(user));
            }
            view.addObject("out", output);
            view.addObject("total", output.getTotal());
            view.addObject("currentPage", input.getCurrentPage());
        });

        return view;
    }

    @RequestMapping("/{uri}")
    public ModelAndView forwardUri(HttpServletRequest request, @PathVariable("uri") String uri) {
        ModelAndView view = new ModelAndView("index");

        Optional<ColumnChannelEnum> channel = ColumnChannelEnum.getColumnChannelByLabel(uri);

        String[] indies = {SpecialColumnIndexEnum.SPECIAL_COLUMN_BLOG_INDEX.getValue()};
        String[] types = {SpecialColumnIndexEnum.SPECIAL_COLUMN_BLOG_TYPE.getValue()};

        Map<String, Class> outputFields = Maps.newHashMap();
        outputFields.put("title", String.class);
        outputFields.put("orig", Integer.class);
        outputFields.put("label", String.class);
        outputFields.put("content", String.class);
        outputFields.put("authorAccount", Long.class);
        outputFields.put("uriMark", Long.class);
        outputFields.put("readNum", Integer.class);
        outputFields.put("collectNum", Integer.class);
        outputFields.put("likesNum", Integer.class);
        outputFields.put("updateDate", Long.class);

        QueryInput input = new QueryInput();
        input.setIndices(indies);
        input.setTypes(types);
        input.setOutputFields(outputFields);

        QueryBuilder queryBuilder = QueryBuilders.boolQuery()
                .must(QueryBuilders.matchPhraseQuery("columnChannel", channel.get().getIndex()));

        ElasticSearchUtils.multipleFieldValueQuery(input, queryBuilder, ResultsVO.class, output -> {
            for (Object o : output.getResults()) {
                ResultsVO vo = (ResultsVO) o;
                userService.getByAccount(vo.getAuthorAccount()).ifPresent(user -> vo.setUser(user));
            }
            view.addObject("out", output);
        });

        view.addObject("topnav", "index");
        LoginStatus.status(request, view);
        view.addObject("columnChannels", ColumnChannelEnum.columnChannels().get());
        //匹配页面渠道列表选中样式class
        view.addObject("uri", channel.get().getLabel());

        return view;
    }
}
